package com.sjzd.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sjzd.server.config.security.JwtTokenUtils;
import com.sjzd.server.mapper.AdminRoleMapper;
import com.sjzd.server.mapper.RoleMapper;
import com.sjzd.server.pojo.Admin;
import com.sjzd.server.mapper.AdminMapper;
import com.sjzd.server.pojo.AdminRole;
import com.sjzd.server.pojo.RespBean;
import com.sjzd.server.pojo.Role;
import com.sjzd.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sjzd
 * @since 2021-02-21
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Override
    public RespBean login(String username, String password, HttpServletRequest req) {
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确！");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("此账号已被禁用，请联系管理员！");
        }
        // 更新security用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null,
                            userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 生成token
        String token = jwtTokenUtils.createTokenByUser(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功！", tokenMap);
    }

    @Override
    public Admin getAdminByUsername(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>()
                .eq("username", username)
                .eq("enabled", true);
        return adminMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Role> getRolesByAdminId(Integer id) {
        return roleMapper.getRolesByAdminId(id);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {
        Admin sysAdmin = (Admin)SecurityContextHolder.getContext().getAuthentication().getDetails();
        Integer id = sysAdmin.getId();
        return adminMapper.getAllAdmins(id, keywords);
    }

    @Override
    @Transactional
    public RespBean updateRolesById(Integer id, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", id));
        int updCount = 0;
        for (Integer rid : rids) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(id);
            adminRole.setRid(rid);
            updCount += adminRoleMapper.insert(adminRole);
        }

        if (updCount == rids.length) {
            return RespBean.success("操作成功！");
        }
        return RespBean.error("操作失败！");
    }
}
